package com.jyniubi.gmail.pms.service.impl;

import com.jyniubi.gmail.pms.entity.AttrEntity;
import com.jyniubi.gmail.pms.mapper.AttrMapper;
import com.jyniubi.gmail.pms.vo.SpuAttrValueVo;
import com.jyniubi.gmail.pms.vo.SpuVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jyniubi.gmail.common.bean.PageResultVo;
import com.jyniubi.gmail.common.bean.PageParamVo;

import com.jyniubi.gmail.pms.mapper.SpuAttrValueMapper;
import com.jyniubi.gmail.pms.entity.SpuAttrValueEntity;
import com.jyniubi.gmail.pms.service.SpuAttrValueService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


@Service("spuAttrValueService")
public class SpuAttrValueServiceImpl extends ServiceImpl<SpuAttrValueMapper, SpuAttrValueEntity> implements SpuAttrValueService {

    @Resource
    private AttrMapper attrMapper;
    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<SpuAttrValueEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<SpuAttrValueEntity>()
        );

        return new PageResultVo(page);
    }

    @Override
    @Transactional
    public void saveBaseAttrValue(SpuVo spu, Long spuId) {
        List<SpuAttrValueVo> baseAttrs = spu.getBaseAttrs();
        if (!CollectionUtils.isEmpty(baseAttrs)){
            this.saveBatch(baseAttrs.stream().map(spuAttrValueVo -> {
                SpuAttrValueEntity spuAttrValueEntity = new SpuAttrValueEntity();
                BeanUtils.copyProperties(spuAttrValueVo,spuAttrValueEntity);
                spuAttrValueEntity.setSpuId(spuId);
                return spuAttrValueEntity;
            }).collect(Collectors.toList()));
        }
    }

    @Override
    public List<SpuAttrValueEntity> querySearchAttrValuesByCidAndSpuId(Long cid, Long spuId) {
        // 先根据分类id category_id 查询出商品的基本类型的检索属性和值
        List<AttrEntity> attrEntities = this.attrMapper.selectList(new QueryWrapper<AttrEntity>()
                .eq("category_id", cid)
                .eq("type", 1)
                .eq("search_type", 1));
        // 判空
        if (CollectionUtils.isEmpty(attrEntities)){
            return null;
        }
        // 把基本类型的id放在集合中
        List<Long> ids = attrEntities.stream().map(AttrEntity::getId).collect(Collectors.toList());
        // 根据spuid 和基本类型的id查询出对应spu 的基本属性
        List<SpuAttrValueEntity> list = this.list(new QueryWrapper<SpuAttrValueEntity>()
                .eq("spu_id", spuId)
                .in("attr_id", ids));
        return list;
    }


}